package com.freeman.cement.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.freeman.cement.entity.ResponseResult;
import com.freeman.cement.exception.AppException;
import com.freeman.cement.exception.AppExceptionCodeMsg;
import com.freeman.cement.mapper.DeptDao;
import com.freeman.cement.entity.Dept;
import com.freeman.cement.service.DeptService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

@Service
public class DeptServiceImpl implements DeptService {

    //引用类型的自动注入@Autowired,@Resource
    @Resource
    private DeptDao deptDao;

    @Override
    public ResponseResult selectAllDept(int pageNo, int pageSize) {
        //验证分页范围
        if (pageNo < 1 || pageSize > 1000) {
            throw new AppException(AppExceptionCodeMsg.PAGE_NO_OR_SIZE_WRONG);
        }
        PageHelper.startPage(pageNo, pageSize, true);
        /*QueryWrapper qw = new QueryWrapper();
        qw.eq("is_duty_room", 0);
        qw.orderByDesc("id");
        List<Dept> depts =deptDao.selectList(qw);*/
        List<Dept> depts = deptDao.selectAllDept();
        PageInfo<Dept> pageInfo = new PageInfo<Dept>(depts);
        return ResponseResult.success(pageInfo);
    }

    @Override
    public ResponseResult selectAllDutyroom(int pageNo, int pageSize) {
        //验证分页范围
        if (pageNo < 1 || pageSize > 1000) {
            throw new AppException(AppExceptionCodeMsg.PAGE_NO_OR_SIZE_WRONG);
        } else {
            // 从当前请求上下文获取用户角色
            ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
            HttpServletRequest request = attributes.getRequest();
            String userRole = (String) request.getAttribute("userRole");
            
            List<Dept> dutys;
            if ("管理员".equals(userRole)) {
                // 管理员可以看到所有值班室
                PageHelper.startPage(pageNo, pageSize, true);
                dutys = deptDao.selectAllDutyroom();
            } else {
                // 值班员只能看到自己所在的值班室，不需要分页
                Integer userId = (Integer) request.getAttribute("userId");
                Dept dutyRoom = deptDao.selectDutyRoomByid(userId);
                dutys = new ArrayList<>();
                if (dutyRoom != null) {
                    dutys.add(dutyRoom);
                }
            }
            
            PageInfo<Dept> pageInfo = new PageInfo<Dept>(dutys);
            return ResponseResult.success(pageInfo);
        }
    }

    @Override
    public ResponseResult getDept(int id) {
        if(id > 0){
            Dept dept = deptDao.selectById(id);
            if(dept != null){
                return ResponseResult.success(dept);
            } else {
                throw new AppException(AppExceptionCodeMsg.ID_NOT_EXISTS);
            }
        } else {
            throw new AppException(AppExceptionCodeMsg.ID_IS_NULL);
        }
    }

    private boolean checekDeptName(String name){
        QueryWrapper<Dept> qw = new QueryWrapper<>();
        qw.select("dept_name").eq("dept_name", name);
        Long a = deptDao.selectCount(qw);
        if (a > 0) {
            throw new AppException(AppExceptionCodeMsg.NAME_EXIST);
        }
        return true;
    }

    private boolean checekDeptCode(String code){
        QueryWrapper<Dept> qw = new QueryWrapper<>();
        qw.select("dept_code").eq("dept_code", code);
        Long a = deptDao.selectCount(qw);
        if (a > 0) {
            throw new AppException(AppExceptionCodeMsg.CODE_EXIST);
        }
        return true;
    }

    /**
     * 新增工段/部门
     * @param dept
     * @return
     */
    @Override
    public ResponseResult addDept(Dept dept) {
        if(dept != null && dept.getDeptName() != null && StringUtils.isNotBlank(dept.getDeptName())){
            //判断工段名是否重复
            checekDeptName(dept.getDeptName());
            //判断工段编号是否重复
            if(dept.getDeptCode() != null && StringUtils.isNotBlank(dept.getDeptCode())){
                checekDeptCode(dept.getDeptCode());
            }
            //存入数据库
            int insert = deptDao.insert(dept);
            if (insert > 0) {
                return ResponseResult.success("新增成功", dept.getId());
            } else
                throw new AppException(AppExceptionCodeMsg.ADD_DEPT_ERROR);
        } else {
            throw new AppException(AppExceptionCodeMsg.CONTENT_IS_NULL);
        }
    }

    @Override
    public ResponseResult deleteDept(int id) {
        if(id > 0){
            Dept dept = deptDao.selectById(id);
            if(dept != null){
                int rslt = deptDao.deleteById(id);
                if(rslt > 0){
                    return ResponseResult.success("删除成功", null);
                } else {
                    throw new AppException(AppExceptionCodeMsg.DELETE_DEPT_ERROR);
                }
            } else {
                throw new AppException(AppExceptionCodeMsg.ID_NOT_EXISTS);
            }
        } else {
            throw new AppException(AppExceptionCodeMsg.ID_IS_NULL);
        }
    }

    @Override
    public ResponseResult updateDept(Dept dept) {
        if(dept != null && dept.getId() != null && dept.getId() > 0){
            Dept old = deptDao.selectById(dept.getId());
            if(old != null){
                if(dept.getDeptName() != null && StringUtils.isNotBlank(dept.getDeptName()) && !dept.getDeptName().equals(old.getDeptName())){
                    checekDeptName(dept.getDeptName());
                }
                if(dept.getDeptCode() != null && StringUtils.isNotBlank(dept.getDeptCode()) && !dept.getDeptCode().equals(old.getDeptCode())){
                    checekDeptCode(dept.getDeptCode());
                }
                dept.setId(old.getId());
                int rslt = deptDao.updateById(dept);
                if(rslt > 0){
                    return ResponseResult.success("修改成功", null);
                } else {
                    throw new AppException(AppExceptionCodeMsg.UPDATE_DEPT_ERROR);
                }
            } else {
                throw new AppException(AppExceptionCodeMsg.ID_NOT_EXISTS);
            }
        } else {
            throw new AppException(AppExceptionCodeMsg.ID_IS_NULL);
        }
    }

}
